package com.example.lt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.lt.context.BaseContext;
import com.example.lt.entity.queryPage.BasePage;
import com.example.lt.entity.video.Type;
import com.example.lt.entity.video.Video;
import com.example.lt.entity.video.VideoShare;
import com.example.lt.service.user.UserService;
import com.example.lt.service.video.TypeService;
import com.example.lt.service.video.VideoService;
import com.example.lt.util.JwtUtil;
import com.example.lt.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/03/18:10
 * version 1.0 注释：
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/joyfulMoments/index")
public class IndexController {

    private final TypeService typeService;

    private final UserService userService;

    private final VideoService videoService;


    /**
     * 推送兴趣视频
     * @param request 请求信息
     * @return
     */
    @GetMapping("/pushVideos")
    public Result pushVideos(HttpServletRequest request) {
        final Long userId = JwtUtil.getUserId(request);
        log.info("用户：{}获取推送视频", userId);
        return Result.ok().data(videoService.pushVideos(userId));
    }

    /**
     * 搜索视频
     * @param searchName 搜索关键字
     * @param basePage 分页信息
     * @param request 请求信息
     * @return
     */
    @GetMapping("/search")
    public Result searchVideo(@RequestParam(required = false) String searchName, BasePage basePage, HttpServletRequest request) {
        log.info("搜索视频：{}", searchName);
        IPage<Video> iPage = videoService.searchVideo(searchName, basePage, JwtUtil.getUserId(request));
        return Result.ok().data(iPage);
    }

    /**
     * 根据视频id获取视频详细信息
     * @param id 视频id
     * @return
     */
    @GetMapping("/video/{id}")
    public Result getVideoById(@PathVariable Long id) {
        log.info("根据视频id：{}获取视频详细信息", id);
        final Long userId = BaseContext.get();
        return Result.ok().data(videoService.getVideoById(id, userId));
    }

    /**
     * 获取热度排行榜
     * @return
     */
    @GetMapping("/video/hot/rank")
    public Result listBHotRank() {
        log.info("获取热度排行榜");
        return Result.ok().data(videoService.hotRank());
    }

    /**
     * 推送热门视频
     * @return
     */
    @GetMapping("/video/hot")
    public Result listHotVideo() {
        log.info("获取热门视频");
        return Result.ok().data(videoService.listHotVideo());
    }

    /**
     * 获取所有分类，如果是登录状态获取则返回结果中还包含每个分类是否被当前用户订阅的情况
     * @param request
     * @return
     */
    @GetMapping("/types")
    public Result getAllTypes(HttpServletRequest request) {
        log.info("获取所有分类");
        // 获取所有分类
        final List<Type> types = typeService.list(new LambdaQueryWrapper<Type>()
                .select(Type::getIcon, Type::getId, Type::getName)
                .orderByDesc(Type::getSort));
        // 如果是登录状态，则能获取到当前登录用户订阅的所有分类的id
        final Set<Long> set = userService.listSubscribeType(JwtUtil.getUserId(request)).stream().map(Type::getId).collect(Collectors.toSet());
        // 遍历所有分类的同时设置用户是否订阅了当前分类
        for (Type type : types) {
            if (set.contains(type.getId())) {
                type.setUsed(true);
            } else {
                type.setUsed(false);
            }
        }
        return Result.ok().data(types);
    }

    /**
     * 分享视频
     * @param videoId
     * @param request
     * @return
     */
    @PostMapping("/share/{videoId}")
    public Result share(@PathVariable Long videoId, HttpServletRequest request) {
        log.info("分享视频");

        String ip = null;
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteUser();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }

        VideoShare videoShare = new VideoShare();
        videoShare.setIp(ip);
        videoShare.setVideoId(videoId);
        if (JwtUtil.checkToken(request)) {
            videoShare.setUserId(JwtUtil.getUserId(request));
        }
        videoService.shareVideo(videoShare);
        return Result.ok();
    }

    /**
     * 根据分类获取视频
     * @param typeId 分类id
     * @return
     */
    @GetMapping("/video/type/{typeId}")
    public Result getVideosByTypeId(@PathVariable Long typeId) {
        log.info("随机获取分类：{}下的视频", typeId);
        return Result.ok().data(videoService.getVideosByTypeId(typeId));
    }

    /**
     * 根据视频标签推送相似视频
     * @param video
     * @return
     */
    @GetMapping("/video/similar")
    public Result pushVideoSimilar(Video video) {
        log.info("根据视频标签推送相似视频：{}",video.getLabelNames());
        return Result.ok().data(videoService.listSimilarVideo(video));
    }

    /**
     * 根据用户id获取公开的视频
     * @param userId 用户id
     * @param basePage 分页信息，page 和 limit
     * @param request 请求信息
     * @return
     */
    @GetMapping("/video/user")
    public Result listVideoByUserId(@RequestParam(required = false) Long userId,
                                    BasePage basePage, HttpServletRequest request) {
        // 判断 userId 是否有效
        userId = userId == null ? JwtUtil.getUserId(request) : userId;
        log.info("分页查询用户：{}的公开视频", userId);
        return Result.ok().data(videoService.listByUserIdOpenVideo(userId, basePage));
    }

    /**
     * 获取用户搜索记录
     * @param request 请求信息
     * @return
     */
    @GetMapping("/search/history")
    public Result searchHistory(HttpServletRequest request) {
        log.info("获取用户历史搜索记录");
        return Result.ok().data(userService.searchHistory(JwtUtil.getUserId(request)));
    }

}
